package com.geeyuu.android.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.geeyuu.android.GeeApplication;
import com.geeyuu.android.GeeConstants;
import com.geeyuu.android.GeePrefrence;
import com.geeyuu.android.R;
import com.geeyuu.android.service.DataKey;
import com.geeyuu.android.service.ProtocolCommand;
import com.geeyuu.android.utils.AndroidUtil;
import com.geeyuu.android.utils.HttpUtil;
import com.geeyuu.android.utils.HttpUtil.HttpUploadListener;
import com.geeyuu.android.utils.LogUtil;

public class RegisterAvatarActivity extends BaseActivity {

    private View popViewContainer;
    private ImageView avatarIamgeView;
    private View anchor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.TAG = "RegisterAvatarActivity";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_avatar_layout);

        super.isForbidBackKey = true;
        GeeApplication geeApplication = (GeeApplication) getApplication();
        geeApplication.addActivity(this);
        
        myHandler = new MyHandler(this);

        initTitleViews();
        initContentViews();

        startBindService();

    }

    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.top_right_button:
                uploadFile();
                break;
            case R.id.avatar_container:
                doAction();
                break;
            case R.id.register_take_photo:
                doAction();
                takePhoto();
                break;
            case R.id.register_pick_photo:
                doAction();
                pickPhoto();
                break;
            case R.id.cancel:
                doAction();
                break;
            }
        }
    };

    private void doAction() {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            popupWindow.showAsDropDown(anchor);
        }
    }

    private void initTitleViews() {

        Button topRightButton = (Button) findViewById(R.id.top_right_button);
        topRightButton.setVisibility(View.VISIBLE);
        topRightButton.setText("完成");
        topRightButton.setOnClickListener(mOnClickListener);

        Button topLeftButton = (Button) findViewById(R.id.top_left_button);
        topLeftButton.setVisibility(View.VISIBLE);
        topLeftButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.logo_icon47, 0);
        topLeftButton.setPadding(AndroidUtil.dip2px(this, 5), 0, 0, 0);
        ViewGroup.LayoutParams vl = topLeftButton.getLayoutParams();
        if (null == vl) {
            vl = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
        } else {
            vl.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            vl.height = ViewGroup.LayoutParams.FILL_PARENT;
        }
        topLeftButton.setLayoutParams(vl);
        topLeftButton.setOnClickListener(mOnClickListener);

        TextView topLeftTextView = (TextView) findViewById(R.id.top_left_text_view);
        topLeftTextView.setText("注册第三步");
        topLeftTextView.setVisibility(View.VISIBLE);
    }

    private void initContentViews() {
        popViewContainer = getLayoutInflater().inflate(R.layout.register_avatar_popup_layout,
                (ViewGroup) findViewById(R.id.all_register_avatar_container), false);

        findViewById(R.id.step_line0).setBackgroundResource(R.drawable.corners_four_blue_bg);
        findViewById(R.id.step_line1).setBackgroundResource(R.drawable.corners_four_blue_bg);
        findViewById(R.id.step_line2).setBackgroundResource(R.drawable.corners_four_blue_bg);

        anchor = findViewById(R.id.avatar_container);
        anchor.setOnClickListener(mOnClickListener);

        avatarIamgeView = (ImageView) findViewById(R.id.register_avatar);

        popViewContainer.findViewById(R.id.register_take_photo).setOnClickListener(mOnClickListener);
        popViewContainer.findViewById(R.id.register_pick_photo).setOnClickListener(mOnClickListener);
        popViewContainer.findViewById(R.id.cancel).setOnClickListener(mOnClickListener);

        popupWindow = new PopupWindow(popViewContainer, WindowManager.LayoutParams.FILL_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);

    }

    private PopupWindow popupWindow;

    private static String photoFilePath = "";
    private static String cropFilePath = "";

    private static final int TAKE_PHOTO_REQUEST_CODE = 1;
    private static final int PICK_PHOTO_REQUEST_CODE = 2;
    private static final int CROP_PHOTO_REQUEST_CODE = 3;

    @Override
    protected void onReceiveMsgFromService(int cmd, Bundle bundle, boolean isMsgNormal) {
        if (cmd == ProtocolCommand.CMD_SET_MY_USER_INFO) {
            if (isMsgNormal) {
                cancelProgressDialog();
                Intent intent = new Intent(RegisterAvatarActivity.this, MainTabActivity.class);
                startActivity(intent);
                GeeApplication geeApplication = (GeeApplication) getApplication();
                geeApplication.clearActivities();
            } else {
                myHandler.sendEmptyMessage(1);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
            case TAKE_PHOTO_REQUEST_CODE:
                File photoFile = new File(photoFilePath);
                if (photoFile.exists() && photoFile.length() > 0) {
                    cropCameraImage(Uri.fromFile(photoFile));
                } else {
                    LogUtil.e(TAG, "拍照回来获取照片失败");
                }
                break;
            case PICK_PHOTO_REQUEST_CODE:
                Uri photoUri = data.getData();
                if (photoUri != null) {
                    cropCameraImage(photoUri);
                } else {
                    LogUtil.e(TAG, "选取照片回来获取Uri失败");
                }
                break;
            case CROP_PHOTO_REQUEST_CODE:
                File cropFile = new File(cropFilePath);
                if (cropFile.exists() && cropFile.length() > 0) {
                    Bitmap avatarBitmap = BitmapFactory.decodeFile(cropFilePath);
                    if (null != avatarBitmap) {
                        File realAvatarFile = new File(GeeConstants.PATH_LARGE_IMAGE_FOLDER, GeeConstants.MY_LARGE_AVATAR_FILE_NAME);
                        realAvatarFile.delete();
                        FileOutputStream fos = null;
                        FileOutputStream fos2 = null;
                        try {
                            realAvatarFile.createNewFile();
                            fos = new FileOutputStream(realAvatarFile);
                            avatarBitmap.compress(CompressFormat.JPEG, 60, fos);
                            avatarIamgeView.setImageBitmap(avatarBitmap);
                            Bitmap thumb = AndroidUtil.getThumbBitmap(getApplicationContext(), avatarBitmap);
                            if(null != thumb){
                                File thumbFile = new File(GeeConstants.PATH_SMALL_IMAGE_FOLDER, GeeConstants.MY_SMALL_AVATAR_FILE_NAME);
                                thumbFile.delete();
                                fos2 = new FileOutputStream(thumbFile);
                                thumb.compress(CompressFormat.JPEG, 60, fos2);
                            }else{
                                LogUtil.e(TAG, "生成缩略图失败");
                            }
                        } catch (Exception e) {
                            LogUtil.e(TAG, "压缩图片失败", e);
                        } finally {
                            if (null != fos) {
                                try {
                                    fos.close();
                                    fos = null;
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            if (null != fos2) {
                                try {
                                    fos2.close();
                                    fos2 = null;
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else {
                        LogUtil.e(TAG, "截图回来读取照片的bitmap为null");
                        AndroidUtil.showToast(getApplicationContext(), "手机内存不足，请在个人界面重新设置");
                    }
                } else {
                    LogUtil.e(TAG, "截图回来获取照片失败");
                    AndroidUtil.showToast(getApplicationContext(), "截取图片失败，请在个人界面重新设置");
                }
                break;
            }
        }
    }

    private MyHandler myHandler = null;
    
    private void uploadFile() {
        final File realAvatarFile = new File(GeeConstants.PATH_LARGE_IMAGE_FOLDER, GeeConstants.MY_LARGE_AVATAR_FILE_NAME);
        if (!realAvatarFile.exists() || realAvatarFile.length() == 0) {
            Intent intent = new Intent(RegisterAvatarActivity.this, MainTabActivity.class);
            startActivity(intent);
            GeeApplication geeApplication = (GeeApplication) getApplication();
            geeApplication.clearActivities();
            return;
        }
        showProgressDialog("设置头像", "正在设置头像，请稍等..", false);
        HttpUtil.postFileForString(GeeConstants.IMG_UPLOAD_HTTP_URL, realAvatarFile, 3, 3000, new HttpUploadListener() {
            @Override
            public void onUploadFinish(final String returnFileId) {
                LogUtil.i(TAG, "上传头像成功");
                if(!realAvatarFile.renameTo(new File(GeeConstants.PATH_LARGE_IMAGE_FOLDER, returnFileId))){
                    LogUtil.e(TAG, "临时头像名字改名为正式名字失败！");
                }
                File thumbFile = new File(GeeConstants.PATH_SMALL_IMAGE_FOLDER, GeeConstants.MY_SMALL_AVATAR_FILE_NAME);
                if(!thumbFile.renameTo(new File(GeeConstants.PATH_SMALL_IMAGE_FOLDER, returnFileId))){
                    LogUtil.e(TAG, "临时小头像名字改名为正式名字失败！");
                }
                GeePrefrence.setMyMainPhotoId(getApplicationContext(), returnFileId);
                myHandler.obtainMessage(0, returnFileId).sendToTarget();
            }
            @Override
            public void onUploadFail() {
                LogUtil.w(TAG, "上传头像失败");
                myHandler.sendEmptyMessage(1);
            }
        });
    }

    private static class MyHandler extends Handler {
        private final WeakReference<RegisterAvatarActivity> registerActivity;

        public MyHandler(Activity activity) {
            registerActivity = new WeakReference<RegisterAvatarActivity>((RegisterAvatarActivity) activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case 0:
                // 更新字段到服务器
                Bundle bundle = new Bundle();
                bundle.putString(DataKey.S_KEY_USERINFO_MAIN_PHOTO_ID, (String) msg.obj);
                registerActivity.get().sendMsgToService(ProtocolCommand.CMD_SET_MY_USER_INFO, bundle);
                break;
            case 1:
                registerActivity.get().cancelProgressDialog();
                AlertDialog.Builder builder = new AlertDialog.Builder(registerActivity.get());
                builder.setTitle("上传头像失败");
                builder.setMessage("是否跳过，稍后在个人中心重设？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(registerActivity.get(), MainTabActivity.class);
                        registerActivity.get().startActivity(intent);
                        GeeApplication geeApplication = (GeeApplication) registerActivity.get().getApplication();
                        geeApplication.clearActivities();
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.create().show();
                break;
            }
        }
    }

    private void takePhoto() {
        if (AndroidUtil.getSdCardAvailSize() < AndroidUtil.MB10) {
            AndroidUtil.showMyToast(this, "手机存储空间不足.");
            return;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File cameraFile = new File(GeeConstants.PATH_TEMP_FILE_FOLDER, "take_temp");
        photoFilePath = cameraFile.getAbsolutePath();
        // if (Config.isSonyErisson()) {
        // intent.putExtra("return-data", true);
        // } else {
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
        startActivityForResult(intent, TAKE_PHOTO_REQUEST_CODE);
    }

    private void pickPhoto() {
        if (AndroidUtil.getSdCardAvailSize() < AndroidUtil.MB5) {
            AndroidUtil.showMyToast(this, "手机存储空间不足.");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, PICK_PHOTO_REQUEST_CODE);
    }

    private void cropCameraImage(Uri photoUri) {
        Intent intent = AndroidUtil.getCropIntent(this);
        intent.setDataAndType(photoUri, "image/*");
        File cropLargeAvatarFile = new File(GeeConstants.PATH_TEMP_FILE_FOLDER, "crop_temp");
        cropLargeAvatarFile.delete();
        cropFilePath = cropLargeAvatarFile.getAbsolutePath();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropLargeAvatarFile));
        startActivityForResult(intent, CROP_PHOTO_REQUEST_CODE);
    }

    @Override
    protected void onDestroy() {
        stopBindService();
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        super.onDestroy();
    }

}
